﻿using AutoMapper;
using MediatR;
using Microsoft.Data.SqlClient;
using S.Authorization.API.Application.Command.OrganizationCommand;
using S.Authorization.API.Application.Command.UserCommand;
using S.Authorization.Domain.Model.Organization;
using S.Authorization.Domain.Model.User;
using S.Authorization.Infrastructure;
using S.Authorization.Infrastructure.Interface.Organization;
using System.Linq;

namespace S.Authorization.API.Application.CommandHandlers.OrganizationCommandHandler
{
    public class ColumnManagementCreateCommandHandler : IRequestHandler<ColumnManagementCreateCommand, bool>,IRequestHandler<FieldModelCreateCommand, int>,IRequestHandler<ColumnManagementDelete,int>
        ,IRequestHandler<FieldModelDelete,int>,IRequestHandler<ColumnDeleteMore, string>,IRequestHandler<ColumUpdate,int>
    {
        private readonly IColumnManagementRepository column;
        private readonly IFieldModelRepository field;
        private readonly DbHelper db;
        private readonly IMapper mapper;
        public ColumnManagementCreateCommandHandler(IColumnManagementRepository _column, IMapper _mapper, IFieldModelRepository _field, DbHelper _db)
        {
            this.column = _column;
            this.mapper = _mapper;
            this.field = _field;
            this.db = _db;
        }
        /// <summary>
        /// 添加栋舍
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<bool> Handle(ColumnManagementCreateCommand request, CancellationToken cancellationToken)
        {
            request.CreateTime=DateTime.Now;
            var list = column.GetAllAsync().Result.FirstOrDefault(x=>x.BuildingName==request.BuildingName&&x.SheepFarm==request.SheepFarm);
            if (list != null)
            {
                return false;
            }
            ColumnManagementModel columns = mapper.Map<ColumnManagementModel>(request);
            return await column.AddAsync(columns);
        }
        /// <summary>
        /// 栏位添加
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<int> Handle(FieldModelCreateCommand request, CancellationToken cancellationToken)
        {
            return await field.AddRangeFieldModelAsync(request.FieldModel);
        }
        /// <summary>
        /// 栏位删除
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<int> Handle(ColumnManagementDelete request, CancellationToken cancellationToken)
        {
            var list = field.GetAllAsync().Result.Where(x => x.BuildingManagementId == request.BuildingManagementId);
            if(list.Count()!=0)
            {
                return 0;
            }else
            {
                string sql = "DELETE from ColumnManagementModel WHERE BuildingManagementId=@BuildingManagementId";
                var parameters = new List<SqlParameter>
                {
                     new SqlParameter("@BuildingManagementId",request.BuildingManagementId),
                };
                int result = await db.ExecuteNonQuery(sql, parameters.ToArray());
                return result;
            }
        }
        /// <summary>
        /// 栏位删除
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<int> Handle(FieldModelDelete request, CancellationToken cancellationToken)
        {

            string sql = "SELECT * FROM FieldModel a JOIN SheepRescission b on a.ColumnManagementId=b.ShiftToHuts WHERE a.ColumnManagementId=@ColumnManagementId";
            var parameters = new List<SqlParameter>
            {
                     new SqlParameter("@ColumnManagementId",request.ColumnManagementId),
            };
            var result =  db.GetListDataBySql<FieldModel>(sql, parameters.ToArray());
            if(result.Result.Count()!=0)
            {
                return 0;
            }
            else
            {
                string sqls = @"DELETE FROM FieldModel WHERE ColumnManagementId=@ColumnManagementId;";
                var parameter = new List<SqlParameter>
                {
                     new SqlParameter("@ColumnManagementId",request.ColumnManagementId),
                };
                int results = await db.ExecuteNonQuery(sqls, parameter.ToArray());
                return results;
            }
        }
        /// <summary>
        /// 栏位批量删除
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<string> Handle(ColumnDeleteMore request, CancellationToken cancellationToken)
        {
            string[] idArray = request.Ids.Split(',');

            List<FieldModel> recordsToDelete = new List<FieldModel>();

            // 检查每个Id对应的集合是否为空
            foreach (string id in idArray)
            {
                // 执行查询操作
                string sql = "SELECT * FROM FieldModel WHERE BuildingManagementId IN (SELECT value FROM STRING_SPLIT(@Ids, ','))";
                var parameter = new List<SqlParameter>
                {
                    new SqlParameter("@ids", id),
                };
                var result = await db.GetListDataBySql<FieldModel>(sql, parameter.ToArray());

                // 判断结果集是否为空
                if (result != null && result.Count() > 0)
                {
                    string write = $"{id}的栋舍正在使用";
                    return write;
                }
                else
                {
                    recordsToDelete.AddRange(result);
                }
            }
            // 执行删除操作
            if (recordsToDelete.Count == 0)
            {
                string deleteSql = "DELETE FROM ColumnManagementModel WHERE BuildingManagementId IN (SELECT value FROM STRING_SPLIT(@Ids, ','))";
                var deleteParameter = new List<SqlParameter>
                {
                    new SqlParameter("@Ids", request.Ids),
                };
                var str = await db.ExecuteNonQuery(deleteSql, deleteParameter.ToArray());
                return str.ToString();
            }
            else
            {
                return "false";
            }
            
        }


        /// <summary>
        /// 栋舍修改
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<int> Handle(ColumUpdate request, CancellationToken cancellationToken)
        {
            string sql = "UPDATE  ColumnManagementModel  SET BuildingTypes=@BuildingTypes,BuildingName=@BuildingName,ResponsiblePerson=@ResponsiblePerson,ProductionPersonnel=@ProductionPersonnel,State=@State,Remark=@Remark,UpdateBy=@UpdateBy,UpdateTime=@UpdateTime,SheepFarmCode=@SheepFarmCode WHERE BuildingManagementId=@BuildingManagementId";
            var parameter = new List<SqlParameter>
            {
                     new SqlParameter("@BuildingTypes",request.BuildingTypes),
                     new SqlParameter("@BuildingName",request.BuildingName),
                     new SqlParameter("@ResponsiblePerson",request.ResponsiblePerson),
                     new SqlParameter("@ProductionPersonnel",request.ProductionPersonnel),
                     new SqlParameter("@State",request.State),
                     new SqlParameter("@Remark",request.Remark),
                     new SqlParameter("@UpdateBy",request.UpdateBy),
                     new SqlParameter("@UpdateTime",DateTime.Now),
                     new SqlParameter("@SheepFarmCode",request.SheepFarmCode),
                     new SqlParameter("@BuildingManagementId",request.BuildingManagementId),
             };
            int results = await db.ExecuteNonQuery(sql, parameter.ToArray());
            return results;
        }
    }
}
